<template>
  <MainLayout title="首页">
    <view class="p-16">
      <view class="title">👋 欢迎，{{ user?.username || '用户' }}</view>

      <view class="grid">
        <view class="card" @click="toTasks('todo')">
          <text class="num">{{ metrics.todo }}</text>
          <text class="label">待办任务</text>
        </view>
        <view class="card" @click="toTasks('done')">
          <text class="num">{{ metrics.doneToday }}</text>
          <text class="label">今日已办</text>
        </view>
        <view class="card warn" @click="toAbnormal">
          <text class="num">{{ metrics.abnormal }}</text>
          <text class="label">不合格提醒</text>
        </view>
      </view>

      <view class="quick">
        <button type="primary" @click="goto('/pages/tasks/fill-manual')">手动填报</button>
        <button @click="goto('/pages/records/index')">我的记录</button>
        <button @click="goto('/pages/reports/index')">报表中心</button>
      </view>
    </view>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { api } from '@/services/api' // 你已有的 api.ts
import MainLayout from '@/layouts/MainLayout.vue'

const user = ref<{username:string}|null>(null)
const metrics = ref({ todo: 0, doneToday: 0, abnormal: 0 })

onMounted(async () => {
  user.value = await api.me()                // 获取当前用户
  const m = await api.homeMetrics()          // 待办/已办/异常数量
  metrics.value = m || metrics.value
})

function toTasks(tab: 'todo'|'done') {
  uni.switchTab({ url: '/pages/tasks/index' })
  // 给任务页一个 tab 切换标记（也可用 Pinia）
  uni.$emit('tasks:setTab', tab)
}

function toAbnormal() {
  uni.switchTab({ url: '/pages/tasks/index' })
  uni.$emit('tasks:filterAbnormal')
}

function goto(url:string) {
  uni.navigateTo({ url })
}
</script>

<style scoped>
.p-16{ padding:16px;}
.title{ font-size:20px; margin-bottom:12px;}
.grid{ display:grid; grid-template-columns: repeat(3,1fr); gap:10px;}
.card{ background:#fff; border-radius:10px; padding:12px; text-align:center; box-shadow:0 2px 8px rgba(0,0,0,.06);}
.card .num{ font-size:22px; font-weight:700;}
.card .label{ display:block; margin-top:6px; color:#666;}
.card.warn{ border:1px solid #ff4d4f;}
.quick{ margin-top:16px; display:flex; gap:10px;}
</style>
